<template>
	<view class="container">
		<!-- 顶部欢迎区域 -->
		<view class="welcome-section">
			<view class="welcome-text">
				<text class="greeting">早上好！</text>
				<text class="username">{{userName}}</text>
			</view>
			<view class="date-info">
				<text class="date">{{currentDate}}</text>
			</view>
		</view>
		
		<!-- 宠物概览卡片 -->
		<view class="pet-overview" v-if="pets.length > 0">
			<view class="section-title">
				<text class="title-text">我的宠物</text>
				<text class="pet-count">({{pets.length}})</text>
			</view>
			<scroll-view class="pet-scroll" scroll-x="true">
				<view class="pet-cards">
					<view 
						class="pet-card" 
						v-for="pet in pets" 
						:key="pet.id"
						@click="viewPetDetail(pet.id)"
					>
						<image 
							:src="pet.photo || '/static/img/default-pet.png'" 
							mode="aspectFill"
							class="pet-avatar"
						></image>
						<text class="pet-name">{{pet.name}}</text>
						<text class="pet-status" :class="getStatusClass(pet.status)">
							{{getStatusText(pet.status)}}
						</text>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<!-- 快捷功能 -->
		<view class="quick-actions">
			<view class="section-title">
				<text class="title-text">快捷功能</text>
			</view>
			<view class="action-grid">
				<view class="action-item" @click="addPet">
					<view class="action-icon add-icon">+</view>
					<text class="action-text">添加宠物</text>
				</view>
				<view class="action-item" @click="goToHealth">
					<view class="action-icon health-icon">❤</view>
					<text class="action-text">健康记录</text>
				</view>
				<view class="action-item" @click="goToLocation">
					<view class="action-icon location-icon">📍</view>
					<text class="action-text">定位追踪</text>
				</view>
				<view class="action-item" @click="goToProfile">
					<view class="action-icon profile-icon">👤</view>
					<text class="action-text">个人中心</text>
				</view>
			</view>
		</view>
		
		<!-- 健康提醒 -->
		<view class="health-reminders" v-if="reminders.length > 0">
			<view class="section-title">
				<text class="title-text">健康提醒</text>
			</view>
			<view class="reminder-list">
				<view 
					class="reminder-item" 
					v-for="reminder in reminders" 
					:key="reminder.id"
				>
					<view class="reminder-icon">🔔</view>
					<view class="reminder-content">
						<text class="reminder-title">{{reminder.title}}</text>
						<text class="reminder-desc">{{reminder.description}}</text>
						<text class="reminder-time">{{reminder.time}}</text>
					</view>
					<view class="reminder-status" :class="reminder.completed ? 'completed' : ''">
						{{reminder.completed ? '已完成' : '待处理'}}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 最近活动 -->
		<view class="recent-activities" v-if="activities.length > 0">
			<view class="section-title">
				<text class="title-text">最近活动</text>
			</view>
			<view class="activity-list">
				<view 
					class="activity-item" 
					v-for="activity in activities" 
					:key="activity.id"
				>
					<view class="activity-icon">{{activity.icon}}</view>
					<view class="activity-content">
						<text class="activity-title">{{activity.title}}</text>
						<text class="activity-time">{{activity.time}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="pets.length === 0">
			<image src="/static/img/empty-home.png" class="empty-image"></image>
			<text class="empty-title">欢迎使用Pawtrack</text>
			<text class="empty-desc">开始添加您的第一个宠物吧！</text>
			<button class="start-btn" @click="addPet">添加宠物</button>
		</view>
	</view>
</template>

<script>
import userStore from '@/store/user.js';
import { getPetList } from '@/api/pet.js';
import { getUserId, checkAndRedirectToLogin } from '@/utils/auth.js';
import { getHealthList } from '@/api/health.js';

export default {
	data() {
		return {
			userName: '',
			currentDate: '',
			pets: [],
			reminders: [],
			activities: []
		}
	},
	onLoad() {
		this.initData()
	},
	onShow() {
		this.updateUserInfo();
		this.loadPets()
		this.loadReminders()
		this.loadActivities()
	},
	methods: {
		updateUserInfo() {
			// 获取用户信息
			const userInfo = userStore.getters['user/userInfo']
			if (userInfo) {
				this.userName = userInfo.nickName || userInfo.userName || '主人';
			} else {
				this.userName = '主人';
			}
		},
		initData() {
			this.updateDate()
			this.loadPets()
			this.loadReminders()
			this.loadActivities()
		},
		
		updateDate() {
			const now = new Date()
			const options = { 
				year: 'numeric', 
				month: 'long', 
				day: 'numeric',
				weekday: 'long'
			}
			this.currentDate = now.toLocaleDateString('zh-CN', options)
		},
		
		async loadPets() {
			try {
				const userId = getUserId();
				
				
				const response = await getPetList(userId);
				
				
				if (response && response.code === 200) {
					// 使用正确的字段名：rows 而不是 data
					const petData = response.rows || response.data || [];
					
					
					// 只显示前5个宠物
					this.pets = petData.slice(0, 5);
					
				} else {
					
					this.pets = [];
				}
			} catch (error) {
				
				this.pets = [];
			}
		},
		
		async loadReminders() {
			try {
				
				
				// 使用统一的认证检查函数
				if (!checkAndRedirectToLogin('请先登录')) {
					return
				}
				
				// 使用正确的健康记录API来获取待处理的健康记录作为提醒
				const response = await getHealthList({
					pageNum: 1,
					pageSize: 10,
					status: '0' // 只获取待处理的记录
				});
				
				
				
				if (response && response.code === 200) {
					const responseData = response.rows || response.data || []
					// 将健康记录转换为提醒格式
					this.reminders = responseData.map(record => ({
						id: record.id,
						title: record.content || record.title || '健康提醒',
						description: record.description || '需要处理的健康记录',
						time: this.formatReminderTime(record.nextRemindTime || record.recordTime),
						completed: record.status === '1'
					}))
					
				} else {
					
					this.loadMockReminders()
				}
			} catch (error) {
				
				this.loadMockReminders()
			}
		},
		
		loadMockReminders() {
				// 使用模拟数据
				this.reminders = [
					{
						id: 1,
						title: '小白需要打疫苗',
						description: '距离上次疫苗已过3个月',
						time: '今天 14:00',
						completed: false
					},
					{
						id: 2,
						title: '旺财体检提醒',
						description: '年度体检时间到了',
						time: '明天 10:00',
						completed: false
					}
				]
		},
		
		async loadActivities() {
			try {
				
				
				// 使用统一的认证检查函数
				if (!checkAndRedirectToLogin('请先登录')) {
					return
				}
				
				// 使用正确的健康记录API来获取最近的健康记录作为活动
				const response = await getHealthList({
					pageNum: 1,
					pageSize: 5 // 只获取最近5条记录
				});
				
				
				
				if (response && response.code === 200) {
					const responseData = response.rows || response.data || []
					// 将健康记录转换为活动格式
					this.activities = responseData.map(record => ({
						id: record.id,
						title: `${record.content || record.title || '健康记录'}已添加`,
						time: this.formatActivityTime(record.createTime || record.recordTime),
						icon: this.getHealthIcon(record.type || record.recordType)
					}))
					
				} else {
					
					this.loadMockActivities()
				}
			} catch (error) {
				
				this.loadMockActivities()
			}
		},
		
		loadMockActivities() {
				// 使用模拟数据
				this.activities = [
					{
						id: 1,
						title: '小白位置更新',
						time: '2分钟前',
						icon: '📍'
					},
					{
						id: 2,
						title: '旺财健康记录已添加',
						time: '1小时前',
						icon: '❤'
					}
				]
		},
		
		formatReminderTime(timeStr) {
			if (!timeStr) return '今天'
			const now = new Date()
			const targetTime = new Date(timeStr)
			const diffTime = targetTime - now
			const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
			
			if (diffDays === 0) return '今天'
			if (diffDays === 1) return '明天'
			if (diffDays === -1) return '昨天'
			return `${Math.abs(diffDays)}天${diffDays > 0 ? '后' : '前'}`
		},
		
		formatActivityTime(timeStr) {
			if (!timeStr) return '刚刚'
			const now = new Date()
			const targetTime = new Date(timeStr)
			const diffTime = now - targetTime
			const diffMinutes = Math.floor(diffTime / (1000 * 60))
			const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
			const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
			
			if (diffMinutes < 1) return '刚刚'
			if (diffMinutes < 60) return `${diffMinutes}分钟前`
			if (diffHours < 24) return `${diffHours}小时前`
			if (diffDays < 7) return `${diffDays}天前`
			return targetTime.toLocaleDateString()
		},
		
		getHealthIcon(type) {
			const icons = {
				'疫苗': '💉',
				'驱虫': '🦠',
				'体检': '🏥',
				'体重': '⚖️',
				'其他': '📋'
			}
			return icons[type] || '❤'
		},
		
		getStatusClass(status) {
			return status === 'online' ? 'status-online' : 'status-offline'
		},
		
		getStatusText(status) {
			return status === 'online' ? '在线' : '离线'
		},
		
		viewPetDetail(petId) {
			uni.navigateTo({
				url: `/pages/pet/detail?id=${petId}`
			})
		},
		
		addPet() {
			uni.navigateTo({
				url: '/pages/pet/add'
			})
		},
		
		goToHealth() {
			uni.switchTab({
				url: '/pages/health/list'
			})
		},
		
		goToLocation() {
			uni.switchTab({
				url: '/pages/location/track'
			})
		},
		
		goToProfile() {
			uni.switchTab({
				url: '/pages/profile/profile'
			})
		}
	}
}
</script>

<style scoped>
.container {
	padding: 20rpx;
	background-color: #f8f9fa;
	min-height: 100vh;
}

.welcome-section {
	background: linear-gradient(135deg, #007AFF, #5856D6);
	border-radius: 20rpx;
	padding: 40rpx;
	margin-bottom: 30rpx;
	color: white;
}

.welcome-text {
	margin-bottom: 20rpx;
}

.greeting {
	font-size: 28rpx;
	opacity: 0.9;
}

.username {
	font-size: 36rpx;
	font-weight: bold;
	margin-left: 10rpx;
}

.date-info {
	font-size: 24rpx;
	opacity: 0.8;
}

.section-title {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.pet-count {
	font-size: 24rpx;
	color: #666;
	margin-left: 10rpx;
}

.pet-overview {
	margin-bottom: 30rpx;
}

.pet-scroll {
	white-space: nowrap;
}

.pet-cards {
	display: flex;
	padding: 10rpx 0;
}

.pet-card {
	background: white;
	border-radius: 15rpx;
	padding: 30rpx;
	margin-right: 20rpx;
	min-width: 200rpx;
	text-align: center;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.pet-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-bottom: 15rpx;
}

.pet-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 10rpx;
}

.pet-status {
	font-size: 22rpx;
	padding: 5rpx 15rpx;
	border-radius: 20rpx;
}

.status-online {
	background: #e8f5e8;
	color: #52c41a;
}

.status-offline {
	background: #f5f5f5;
	color: #999;
}

.quick-actions {
	margin-bottom: 30rpx;
}

.action-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 20rpx;
}

.action-item {
	background: white;
	border-radius: 15rpx;
	padding: 30rpx 20rpx;
	text-align: center;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.action-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
	margin: 0 auto 15rpx;
}

.add-icon {
	background: #007AFF;
	color: white;
}

.health-icon {
	background: #ff6b6b;
	color: white;
}

.location-icon {
	background: #4ecdc4;
	color: white;
}

.profile-icon {
	background: #45b7d1;
	color: white;
}

.action-text {
	font-size: 24rpx;
	color: #333;
}

.health-reminders {
	margin-bottom: 30rpx;
}

.reminder-list {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
}

.reminder-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.reminder-item:last-child {
	border-bottom: none;
}

.reminder-icon {
	font-size: 30rpx;
	margin-right: 20rpx;
}

.reminder-content {
	flex: 1;
}

.reminder-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 5rpx;
}

.reminder-desc {
	font-size: 24rpx;
	color: #666;
	display: block;
	margin-bottom: 5rpx;
}

.reminder-time {
	font-size: 22rpx;
	color: #999;
}

.reminder-status {
	font-size: 22rpx;
	padding: 5rpx 15rpx;
	border-radius: 20rpx;
	background: #fff2e8;
	color: #fa8c16;
}

.reminder-status.completed {
	background: #f6ffed;
	color: #52c41a;
}

.recent-activities {
	margin-bottom: 30rpx;
}

.activity-list {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
}

.activity-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.activity-item:last-child {
	border-bottom: none;
}

.activity-icon {
	font-size: 30rpx;
	margin-right: 20rpx;
}

.activity-content {
	flex: 1;
}

.activity-title {
	font-size: 28rpx;
	color: #333;
	display: block;
	margin-bottom: 5rpx;
}

.activity-time {
	font-size: 22rpx;
	color: #999;
}

.empty-state {
	text-align: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 300rpx;
	height: 300rpx;
	margin-bottom: 40rpx;
}

.empty-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 20rpx;
}

.empty-desc {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 40rpx;
}

.start-btn {
	background: #007AFF;
	color: white;
	padding: 25rpx 50rpx;
	border-radius: 15rpx;
	border: none;
	font-size: 30rpx;
}
</style>